#!/usr/bin/env bash
# unpack: Extract common file formats
 
# Dependencies: unrar, unzip, p7zip-full

# Author: Patrick Brisbin
# From: http://linuxtidbits.wordpress.com/2009/08/04/week-of-bash-scripts-extract/

# Display usage if no parameters given
if [[ -z "$@" ]]; then
	echo " ${0##*/} <archive> - extract common file formats)"
	exit
fi
 
# Required program(s)
req_progs=(7z unrar unzip)
for p in ${req_progs[@]}; do
	hash "$p" 2>&- || \
	{ echo >&2 " Required program \"$p\" not installed."; exit 1; }
done
 
# Test if file exists
if [ ! -f "$@" ]; then
	echo "File "$@" doesn't exist"
	exit
fi
 
# Extract file by using extension as reference
case "$@" in
	*.7z ) 7z x "$@" ;;
	*.tar.bz2 ) tar xvjf "$@" ;;
	*.bz2 ) bunzip2 "$@" ;;
	*.deb ) ar vx "$@" ;;
	*.tar.gz ) tar xvf "$@" ;;
	*.gz ) gunzip "$@" ;;
	*.tar ) tar xvf "$@" ;;
	*.tbz2 ) tar xvjf "$@" ;;
	*.tar.xz ) tar xvf "$@" ;;
	*.tgz ) tar xvzf "$@" ;;
	*.rar ) unrar x "$@" ;;
	*.zip ) unzip "$@" ;;
	*.Z ) uncompress "$@" ;;
	* ) echo " Unsupported file format" ;;
esac
